<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    @close="onClose"
    :title="state.title"
    width="920px"
    :maskClosable="false"
    :headerStyle="{ borderBottom: 0 }"
  >
    <template #footer>
      <a-flex v-if="chooseCard == false" justify="center"></a-flex>
      <a-flex v-else gap="small" align="center" justify="center" style="height: 100%">
        <a-button danger @click="onClose()">关闭</a-button>
        <a-button v-if="getTimesCardCanPostpone(state.record)" type="primary" @click="onPostpone"
          >卡延期</a-button
        >
        <!-- <a-button type="primary" v-if="state.record.delayFlag === 1" @click="onPostpone"
          >卡延期</a-button
        > -->
        <a-button type="primary" v-if="state.record.expireFlag > 1" @click="onUpgrade"
          >卡升级</a-button
        >
        <a-button type="primary" v-if="state.record.expireFlag > 1" @click="onExpendCard"
          >耗卡</a-button
        >
        <a-button
          type="primary"
          v-if="state.record.expireFlag > 1 && state.detail?.giftFlag !== 1"
          @click="onOrderRefund3"
          >退卡</a-button
        >
        <a-button
          v-if="state.detail?.cardType === '100' && state.record.expireFlag > 1"
          type="primary"
          @click="onRecharge"
        >
          卡续充
        </a-button>
      </a-flex>
    </template>

    <a-flex justify="center">
      <card-head :item="state.record" />
    </a-flex>
    <a-tabs v-model:activeKey="state.tabKey" type="line" size="large" class="mt-1">
      <a-tab-pane
        v-for="o in state.detail?.cardType === '100'
          ? ocbList.filter((o) => o.value !== '2')
          : ocbList"
        :key="o.value"
        :tab="o.label"
      >
        <template v-if="o.value === '1'">
          <table style="width: 100%">
            <tr
              style="
                height: 54px;
                background: #f7f7f7;
                font-weight: bold;
                box-shadow: inset 0 -1px 0 0 #e5e5e5;
              "
            >
              <td style="text-align: center"> 商品信息 </td>
              <template v-if="state.detail?.cardType === '100'">
                <td> 数量 </td>
                <td> 卡金额 </td>
              </template>
              <td v-else> 耗卡次数 </td>
              <td> 订单编号 </td>
              <td v-if="state.detail?.cardType !== '100'"> 美容师 </td>
              <td>
                {{ state.detail?.cardType === '100' ? '下单时间' : '服务时间' }}
              </td>
              <td> 制单人 </td>
            </tr>

            <tr
              v-for="(item, index) in state.detail?.cardConsumeDetailsList"
              :key="index"
              style="background: #ffffff; box-shadow: inset 0 -1px 0 0 #e5e5e5"
            >
              <td style="padding: 8px 6px">
                <pro-img-cell
                  :src="item.goodsImage"
                  :title="item.goodsName"
                  :price="item.goodsPrice"
                />
              </td>
              <template v-if="state.detail?.cardType === '100'">
                <td> X {{ item.usedQty || '1' }} </td>
                <td :class="{ 'text-[#31B89A]': item.usedPrice < 0 }">
                  {{ item.usedPrice >= 0 ? '-' : '+' }} ¥
                  {{
                    round(Math.abs((item.usedQty < 0 ? item.usedPrice : item.cardUsedPrice) || 0))
                  }}
                </td>
              </template>
              <td v-else>
                {{ item.usedQty || '0' }}
              </td>
              <td class="cursor-pointer" style="color: #e4a7ba">
                <span @click="openDetail(item)">{{ item.orderSn || '-' }}</span>
              </td>
              <td v-if="state.detail?.cardType !== '100'">
                {{ item.employeeName || '-' }}
              </td>
              <td>
                {{ item.transDatetime || '-' }}
              </td>
              <td>
                {{ item.createBy || '-' }}
              </td>
            </tr>
          </table>
          <div v-if="!state.detail?.cardConsumeDetailsList?.length" class="text-center">
            <a-empty :image="simpleImage" />
          </div>
        </template>
        <template v-else-if="o.value === '2'">
          <table style="width: 100%">
            <tr
              style="
                height: 54px;
                background: #f7f7f7;
                box-shadow: inset 0 -1px 0 0 #e5e5e5;
                font-weight: bold;
              "
            >
              <td style="text-align: center"> 服务名称 </td>
              <td> 服务时长 </td>
              <td> 服务价格 </td>
              <td> 可用次数 </td>
            </tr>
            <tr
              v-for="(item, index) in state.detail?.cardTimesGoodsList"
              :key="index"
              style="background: #ffffff; box-shadow: inset 0 -1px 0 0 #e5e5e5"
            >
              <td style="padding: 8px 6px">
                <pro-img-cell :src="item.serviceGoodsImage" :title="item.goodsName"></pro-img-cell>
              </td>
              <td> {{ item.duration || '0' }}分钟 </td>
              <td>
                {{ item.salePrice || '-' }}
              </td>
              <td>
                {{ item.qty || '0' }}
              </td>
            </tr>
          </table>
          <div v-if="!state.detail?.cardTimesGoodsList?.length" class="text-center">
            <a-empty :image="simpleImage" />
          </div>
        </template>

        <template v-else-if="o.value === '3'">
          <div class="card-sub-type" style="padding-bottom: 12px">
            <div
              :class="['use', 'cell', state.tabKey2 === o2.value ? 'active' : 'tacit']"
              v-for="o2 in proCategoryType2 ?? []"
              :key="o2.value"
              @click="state.tabKey2 = o2.value"
            >
              <div class="label">{{ o2.label }}</div>
            </div>
          </div>

          <template v-if="state.tabKey2 === 'P'">
            <table style="width: 100%">
              <tr
                style="
                  font-weight: bold;
                  height: 54px;
                  background: #f7f7f7;
                  box-shadow: inset 0 -1px 0 0 #e5e5e5;
                "
              >
                <td style="text-align: center"> 产品名称 </td>
                <td> 规格 </td>
                <td> 售卖价格 </td>
                <td> 赠送数量 </td>
              </tr>
              <tr
                v-for="(item, index) in state.detail?.memberBenefitsBeanList?.filter(
                  (z) => z.benefitsType === state.tabKey2,
                )"
                :key="index"
                style="background: #ffffff; box-shadow: inset 0 -1px 0 0 #e5e5e5"
              >
                <td style="padding: 8px 6px">
                  <pro-img-cell :src="item.productImage" :title="item.benefitsName"></pro-img-cell>
                </td>
                <td>
                  {{ item.productSpecs || '-' }}
                </td>
                <td>
                  {{ item.productSalePrice || '-' }}
                </td>
                <td>
                  {{ item.benefitsQty || '0' }}
                </td>
              </tr>
            </table>
            <div v-if="!state.detail?.memberBenefitsBeanList?.length" class="text-center">
              <a-empty :image="simpleImage" description="暂无商品" />
            </div>
          </template>

          <template v-else-if="state.tabKey2 === 'S'">
            <table style="width: 100%">
              <tr style="height: 54px; background: #f7f7f7; box-shadow: inset 0 -1px 0 0 #e5e5e5">
                <td style="text-align: center"> 服务名称 </td>
                <td> 服务时长 </td>
                <td> 售卖价格 </td>
                <td> 赠送数量 </td>
              </tr>
              <tr
                v-for="(item, index) in state.detail?.memberBenefitsBeanList?.filter(
                  (z) => z.benefitsType === state.tabKey2,
                )"
                :key="index"
                style="background: #ffffff; box-shadow: inset 0 -1px 0 0 #e5e5e5"
              >
                <td style="padding: 8px 6px">
                  <pro-img-cell :src="item.serviceImage" :title="item.benefitsName"></pro-img-cell>
                </td>
                <td> {{ item.duration || '0' }}分钟 </td>
                <td>
                  {{ item.serviceSalePrice || '-' }}
                </td>
                <td>
                  {{ item.benefitsQty || '0' }}
                </td>
              </tr>
            </table>
            <div v-if="!state.detail?.memberBenefitsBeanList?.length" class="text-center">
              <a-empty :image="simpleImage" description="暂无商品" />
            </div>
          </template>

          <template v-else-if="state.tabKey2 === 'C'">
            <table style="width: 100%">
              <tr style="height: 54px; background: #f7f7f7; box-shadow: inset 0 -1px 0 0 #e5e5e5">
                <td style="text-align: center"> 卡项名称 </td>
                <td> 卡项类型 </td>
                <td> 售卖价格 </td>
                <td> 赠送数量 </td>
              </tr>
              <tr
                v-for="(item, index) in state.detail?.memberBenefitsBeanList?.filter(
                  (z) => z.benefitsType === state.tabKey2,
                )"
                :key="index"
                style="background: #ffffff; box-shadow: inset 0 -1px 0 0 #e5e5e5"
              >
                <td style="padding: 8px 6px">
                  <pro-img-cell :src="item.cardImage" :title="item.benefitsName"></pro-img-cell>
                </td>
                <td>
                  <!-- {{ getChildrenLabel(proCardType, item.cardType, item.cardSubType) || '-' }} -->
                  {{ item.cardTypeName || '-' }}
                </td>
                <td>
                  {{ item.cardSalePrice || '-' }}
                </td>
                <td>
                  {{ item.benefitsQty || '0' }}
                </td>
              </tr>
            </table>
            <div v-if="!state.detail?.memberBenefitsBeanList?.length" class="text-center">
              <a-empty :image="simpleImage" description="暂无商品" />
            </div>
          </template>
        </template>
      </a-tab-pane>
    </a-tabs>

    <div
      class="mb-5"
      style="font-weight: 500; font-size: 16px; color: #333333; padding: 24px 0 0px 0"
      >卡订单信息
    </div>

    <a-row :gutter="12">
      <a-col :span="3" class="f-label"> 订单编号</a-col>
      <a-col :span="9" class="f-value">
        {{ state.detail?.cardOrderInfo?.[0]?.openOrderSn ?? '--' }}
      </a-col>

      <a-col :span="3" class="f-label"> 下单时间</a-col>
      <a-col :span="9" class="f-value">
        {{ state.detail?.cardOrderInfo?.[0]?.saleDate ?? '--' }}
      </a-col>
    </a-row>

    <a-row :gutter="12" style="padding: 12px 0">
      <a-col :span="3" class="f-label"> 制单人</a-col>
      <a-col :span="9" class="f-value">
        {{ state.detail?.cardOrderInfo?.[0]?.salesCode ?? '--' }}
      </a-col>
    </a-row>

    <CardRecharge @register="registerCardRecharge" @complete="loadData" />
    <CardPostpone @register="registerCardPostpone" @complete="loadData" />
    <OrderRefund3 @register="registerRefund3" />
    <OrderDetail @register="registerDetail" />
    <back-detail @register="registerDetail1" />
  </BasicDrawer>
</template>
<script setup>
  import { reactive } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner } from '@/components/Drawer';
  import OrderDetail from '../cashier/order-detail.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import CardHead from '@/views/member/card-head.vue';
  import { getChildrenLabel, ocbList, proCardType, proCategoryType2 } from '@/api/ds.js';
  import { POST } from '@/api/http.js';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import CardRecharge from './card-recharge.vue';
  import CardPostpone from './card-postpone.vue';
  import { useModal } from '@/components/Modal';
  import { useRouter } from 'vue-router';
  import OrderRefund3 from '../cashier/order-refund-3.vue';
  import { exist } from '@/api/util.js';
  import { round } from '@/api/util.js';
  import BackDetail from '@/views/member/back-detail.vue';
  import { Empty } from 'ant-design-vue';
  import { usePaddingOrder } from './use-padding-order';
  import { getTimesCardCanPostpone } from '@/views/member/util.js';

  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

  const router = useRouter();

  const [registerCardRecharge, { openDrawer: cardRechargeDrawer }] = useDrawer();
  const [registerCardPostpone, { openModal: cardRechargeModal }] = useModal();

  const [registerRefund3, { openDrawer: refundDrawer3 }] = useDrawer();
  const [registerDetail, { openDrawer: registerOrder }] = useDrawer();
  const [registerDetail1, { openDrawer: TDlDrawer }] = useDrawer();

  const startOrder = usePaddingOrder();

  async function openDetail(record) {
    console.log(record);
    if (record.orderSn?.includes('TD')) {
      const res =
        (await POST('/cashier/getMasterOrderDetailsBean', {
          masterOrderSn: record.orderSn,
          memberCode: state.memberCode,
        })) ?? {};
      TDlDrawer(true, { record: res });
    } else {
      registerOrder(true, { masterOrderSn: record.orderSn });
    }
  }
  const state = reactive({
    title: '',
    memberCode: null,
    tabKey: '1',
    tabKey2: 'P',
    record: {},
    detail: {},
  });

  let records = '';

  let chooseCard = '';

  const { createMessage } = useMessage();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(
    async ({ choose, memberCode, record }) => {
      chooseCard = choose;
      records = record;
      Object.assign(state, { title: '客户权益', memberCode, record });
      await loadData();
    },
  );

  async function loadData() {
    const { memberCode, record } = state;
    const { cardNo } = record;

    state.detail =
      (
        await POST('/card/getUserOneCardBenefitsInfo', {
          memberCode,
          cardNo,
        })
      )?.userCardPack ?? {};
    state.record = state.detail;
  }

  const emit = defineEmits(['complete']);

  const onClose = () => {
    emit('complete');
    closeDrawer();
  };
  function onRecharge() {
    const { memberCode, record } = state;
    console.log(state, 'state', state.detail?.cardOrderInfo?.[0]);
    cardRechargeDrawer(true, {
      memberCode,
      record,
      masterOrderSn: state.detail?.cardOrderInfo?.[0]?.openOrderSn,
    });
  }

  function onPostpone() {
    const { memberCode, record } = state;
    cardRechargeModal(true, { memberCode, record });
  }

  async function onOrderRefund3() {
    const orderInfo = state.detail?.cardOrderInfo?.[0];
    if (!orderInfo) {
      return;
    }

    const { memberCode } = state;
    const { cardNo } = state.record;
    const { openOrderSn: masterOrderSn } = orderInfo;

    const orderHeader =
      (await POST('/cashier/getMasterOrderDetailsBean', {
        masterOrderSn,
        memberCode,
      })) ?? {};

    const orderLine = orderHeader.responseMasterOrderItemBeanList?.find((o) =>
      exist(cardNo, o.goodsExtendedCode?.split(',') ?? []),
    );
    const cardItem = state.record;

    orderLine.itemGoodsType = 3;
    const data = { orderHeader, record: orderLine, cardItem };
    console.log(data, 'data');
    refundDrawer3(true, data);
  }

  async function onExpendCard() {
    const { memberCode } = state;
    const { cardNo, id, cardType, cardSubType } = state.record;

    const params = { memberCode, cardNo, cardSubType };

    if (cardType === '100') {
      params.consumption = id;
    }

    startOrder(params);
  }

  async function onUpgrade() {
    const { memberCode } = state;
    const { cardNo } = state.record;
    router.push(
      `/member/list/card-upgrade?memberCode=${memberCode || '-1'}&cardNo=${cardNo || ''}`,
    );
  }
</script>

<style lang="less" scoped>
  .card-sub-type {
    display: flex;
    position: relative;
    flex-flow: row wrap;
    align-items: center;
    cursor: pointer;
    gap: 8px;

    .cell {
      padding: 4px 20px;
      border-radius: 32px;
      font-size: 14px;
      font-weight: 400;
      text-align: center;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 3px solid @primary-color;
      background-color: @primary-color;
      color: #fff;

      .desc {
        color: #fff;
      }
    }
  }
</style>
